import { defineStore } from 'pinia';
import axios from '@/plugins/axios';

// 部门数据接口
export interface Department {
  id: number;
  name: string;
  description: string;
  createTime: string;
}

// 部门表单字段配置
export const departmentFields = [
  { key: 'name', label: '部门名称', type: 'text', placeholder: '请输入部门名称', maxLength: 50, },
  { key: 'description', label: '部门描述', type: 'textarea', placeholder: '请输入部门描述', maxLength: 500, },
];

export const useDepartmentStore = defineStore('department', {
  state: () => ({
    departments: [] as Department[],
  }),
  actions: {
    // 获取部门列表
    async fetchDepartments() {
      try {
        const response = await axios.get('/departments');
        if (response.data.code === 200) {
          this.departments = response.data.data;
          return this.departments;
        }
        throw new Error(response.data.message || '获取部门列表失败');
      } catch (error) {
        throw new Error('获取部门列表失败');
      }
    },
    // 创建部门
    async createDepartment(data: { name: string; description: string }) {
      const response = await axios.post('/departments', data);
      if (response.data.code === 200) {
        return response.data.data;
      }
      throw new Error(response.data.message || '创建部门失败');
    },
    // 更新部门
    async updateDepartment(data: Department) {
      const response = await axios.put('/departments', data);
      if (response.data.code === 200) {
        return response.data.data;
      }
      throw new Error(response.data.message || '更新部门失败');
    },
    // 删除部门
    async deleteDepartment(id: number) {
      const response = await axios.delete(`/departments/${id}`);
      if (response.data.code === 200) {
        return response.data.data;
      }
      throw new Error(response.data.message || '删除部门失败');
    },
  },
});
